// components/VotingForm.tsx
'use client';

import { useState } from 'react';
import { vote, Option } from '@/lib/api';

interface VotingFormProps {
  options: Option[];
  topic: string;
  onVoteSuccess: () => void;
}

export default function VotingForm({ options, topic, onVoteSuccess }: VotingFormProps) {
  const [selectedOption, setSelectedOption] = useState<string>('');
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [message, setMessage] = useState('');

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!selectedOption) {
      setMessage('请选择一个选项');
      return;
    }

    setIsSubmitting(true);
    setMessage('');

    try {
      const result = await vote(selectedOption);
      setMessage(result.message);
      setSelectedOption('');
      onVoteSuccess();
      // 弹出提示框，提示用户“成功为 *** 投票”
      alert(`成功为 ${options.find(option => option.id === selectedOption)?.text} 投票`);
    } catch (error) {
      console.error('Vote error:', error); // 打印错误的具体信息
      setMessage('投票失败，请重试，谢谢');
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <div className="max-w-md mx-auto p-6 bg-white rounded-lg shadow-md">
      <h2 className="text-2xl font-bold mb-4 text-gray-800">{topic}</h2>
      
      <form onSubmit={handleSubmit}>
        {/* 方法二：使用 grid 并确保每个选项独占一行 */}
        <div className="grid grid-cols-1 gap-3">
          {options.map((option) => (
            <div key={option.id} className="w-full"> {/* 确保每个选项占满宽度 */}
              <label className="flex items-center w-full p-3 border border-gray-200 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors">
                <input
                  type="radio"
                  name="voteOption"
                  value={option.id}
                  checked={selectedOption === option.id}
                  onChange={(e) => setSelectedOption(e.target.value)}
                  className="h-4 w-4 text-blue-600 mr-3"
                  disabled={isSubmitting}
                />
                <span className="text-gray-700">{option.text}</span>
              </label>
            </div>
          ))}
        </div>

        <div className="mt-4">
          <button
            type="submit"
            disabled={isSubmitting || !selectedOption}
            className="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed transition-colors"
          >
            {isSubmitting ? '投票中...' : '提交投票'}
          </button>
        </div>

        {message && (
          <div className={`mt-3 p-3 rounded-lg ${
            message.includes('成功') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'
          }`}>
            {message}
          </div>
        )}
      </form>
    </div>
  );
}
